package com.kasinf.sample.protect.config;

import cn.hutool.crypto.SecureUtil;
import com.kasinf.framework.common.util.http.IpUtils;
import com.kasinf.framework.idempotent.core.annotation.Idempotent;
import com.kasinf.framework.idempotent.core.keyresolver.IdempotentKeyResolver;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 自定义幂等key解析器
 *
 * @Author : Kaiser
 * @Date: 2025/6/10  19:10
 */
public class CustomIdempotentKeyResolver implements IdempotentKeyResolver {
    @Override
    public String resolver(JoinPoint joinPoint, Idempotent idempotent) {
        String methodName = joinPoint.getSignature().toString();
        HttpServletRequest request = getCurrentHttpRequest();
        if (request == null) {
            return SecureUtil.md5(methodName);
        }
        String ip = IpUtils.getIpAddr(request);
        return SecureUtil.md5(methodName + ip);
    }

    public static HttpServletRequest getCurrentHttpRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        }
        return null;
    }
}
